import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login as loginApi, getCurrentUser } from '@/api/auth'
import type { LoginRequest, User } from '@/types'
import { ElMessage } from 'element-plus'

type MessageType = 'success' | 'warning' | 'info' | 'error'

interface LogoutOptions {
  /**
   * 是否展示提示消息，默认展示
   */
  showMessage?: boolean
  /**
   * 自定义提示文本，未提供时根据类型使用默认文案
   */
  message?: string
  /**
   * 提示类型，默认 success
   */
  messageType?: MessageType
}

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref<User | null>(null)
  const accessToken = ref<string | null>(localStorage.getItem('access_token'))
  const refreshToken = ref<string | null>(localStorage.getItem('refresh_token'))
  const isAuthenticated = ref<boolean>(!!accessToken.value)

  // 登录
  async function login(credentials: LoginRequest) {
    try {
      const response = await loginApi(credentials)
      
      // 保存 token
      accessToken.value = response.access
      refreshToken.value = response.refresh
      localStorage.setItem('access_token', response.access)
      localStorage.setItem('refresh_token', response.refresh)
      isAuthenticated.value = true

      // 获取用户信息并检查权限
      const hasPermission = await fetchUserInfo()
      
      if (!hasPermission) {
        // 如果没有权限，清除token并返回失败
        return false
      }

      ElMessage.success('登录成功')
      return true
    } catch (error) {
      ElMessage.error('登录失败')
      return false
    }
  }

  // 获取用户信息
  async function fetchUserInfo() {
    try {
      const userInfo = await getCurrentUser()
      
      // 检查用户是否是管理员
      if (!userInfo.is_staff) {
        ElMessage.error('Access denied: Admin privileges required')
        logout({ showMessage: false })
        return false
      }
      
      user.value = userInfo
      return true
    } catch (error) {
      console.error('Failed to fetch user info:', error)
      // 如果获取用户信息失败，可能是权限问题，自动登出
      logout({ showMessage: false })
      return false
    }
  }

  // 登出
  function logout(options: LogoutOptions = {}) {
    const { showMessage = true, message, messageType = 'success' } = options

    user.value = null
    accessToken.value = null
    refreshToken.value = null
    isAuthenticated.value = false
    localStorage.removeItem('access_token')
    localStorage.removeItem('refresh_token')

    if (showMessage) {
      ElMessage({
        type: messageType,
        message: message ?? (messageType === 'success' ? '已退出登录' : '登录状态已过期，请重新登录')
      })
    }
  }

  return {
    user,
    accessToken,
    refreshToken,
    isAuthenticated,
    login,
    logout,
    fetchUserInfo
  }
})
